package com.yt.product.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.product.models.dto.ProductInfoDTO;
import com.yt.product.models.service.IProductInfoService;
import com.yt.product.models.vo.ProductCategoryTreeVO;
import com.yt.product.models.vo.ProductCategoryVO;
import com.yt.product.models.vo.ProductInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.product.models.service.IProductCategoryService;
import com.yt.product.models.bo.ProductCategoryBO;
import com.yt.product.models.bo.ProductCategorySaveBO;
import com.yt.product.models.dto.ProductCategoryDTO;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/productCategory")
@Slf4j
@Api(value = "ProductCategoryApiController", tags = "产品类型信息Api接口")
public class ProductCategoryApiController {

    @DubboReference
    private IProductCategoryService productCategoryService;

    @DubboReference
    private IProductInfoService productInfoService;

    @ApiOperation(value = "新增产品类型", notes = "新增产品类型信息")
    @PostMapping("/add")
    public Result<ProductCategoryVO> add(@RequestBody ProductCategorySaveBO saveBO) {
        boolean success = productCategoryService.add(saveBO);
        if (success) {
            // 查询刚插入的记录（按名称和状态唯一标识）
            ProductCategoryDTO dto = productCategoryService.selectOne(
                    new EntityWrapper<ProductCategoryDTO>()
                            .eq("category_name", saveBO.getCategoryName())
                            .eq("status", saveBO.getStatus())
                            .orderBy("create_time", false)
                            .last("LIMIT 1")
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010);
            }
            return new Result<>(convertToVO(dto));
        }
        return new Result<>(CodeEnum.FAIL_100007);
    }

    @ApiOperation(value = "更新产品类型", notes = "根据ID更新产品类型信息")
    @PutMapping("/update/{id}")
    public Result<ProductCategoryVO> update(
            @PathVariable Long id,
            @RequestBody ProductCategorySaveBO saveBO) {

        // 校验记录是否存在
        ProductCategoryDTO existingDto = productCategoryService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        // 复制更新字段
        ProductCategoryDTO updateDto = new ProductCategoryDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setUpdateTime(new Date());

        boolean success = productCategoryService.updateById(updateDto);
        if (success) {
            return new Result<>(convertToVO(productCategoryService.selectById(id)));
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "删除产品类型", notes = "物理删除产品类型信息")
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable Long id) {
        // 校验记录是否存在
        if (productCategoryService.selectById(id) == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }
        boolean success = productCategoryService.deleteById(id);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }


    @ApiOperation(value = "查询产品类型详情", notes = "根据ID查询产品类型详情")
    @GetMapping("/get/{id}")
    public Result<ProductCategoryVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        ProductCategoryDTO dto = productCategoryService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }
        return new Result<>(convertToVO(dto));
    }

    @ApiOperation(value = "查询产品类型列表（分页）", notes = "查询所有产品类型列表（支持分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<ProductCategoryVO>> list(
            ProductCategoryBO bo,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象
        Page<ProductCategoryDTO> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        Wrapper<ProductCategoryDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null) {
            wrapper.eq("status", bo.getStatus());
        }
        if (bo.getStartDate() != null) {
            wrapper.ge("createtime", bo.getStartDate());
        }
        if (bo.getEndDate() != null) {
            wrapper.le("createtime", bo.getEndDate());
        }

        // 执行分页查询
        Page<ProductCategoryDTO> resultPage = productCategoryService.selectPage(page, wrapper);

        // DTO转VO处理
        List<ProductCategoryVO> voList = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 封装分页结果
        Page<ProductCategoryVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        voPage.setRecords(voList);

        return new Result<>(voPage);
    }

    private ProductCategoryVO convertToVO(ProductCategoryDTO dto) {
        if (dto == null) {
            return null;
        }
        ProductCategoryVO vo = new ProductCategoryVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }


    @ApiOperation(value = "按名称模糊查询产品分类", notes = "根据产品分类名称模糊查询所有匹配结果")
    @ApiImplicitParam(name = "categoryName", value = "分类名称（模糊匹配）", paramType = "query", dataType = "String")
    @GetMapping("/searchByName")
    public Result<List<ProductCategoryVO>> searchByNameNoPage(String categoryName) {
        EntityWrapper<ProductCategoryDTO> wrapper = new EntityWrapper<>();
        if (StrUtils.isNotEmpty(categoryName)) {
            wrapper.like("category_name", categoryName);
        }
        wrapper.eq("status", 1); // 只查询启用状态的分类

        // 查询所有匹配结果
        List<ProductCategoryDTO> dtoList = productCategoryService.selectList(wrapper);

        // DTO转VO
        List<ProductCategoryVO> voList = dtoList.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return new Result<>(voList);
    }
    private ProductInfoVO convertToProductVO(ProductInfoDTO dto) {
        if (dto == null) return null;
        ProductInfoVO vo = new ProductInfoVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }


}